import { release } from "node:os";
import { fileURLToPath } from "node:url";
import { join, dirname } from "node:path";
import {
  app,
  shell,
  ipcMain,
  BrowserWindow,
  Menu
} from "electron";
// import { autoUpdater } from "electron-updater";
import pkg from "electron-updater";
const { autoUpdater } = pkg;
// 导入我们创建的模块
import NotificationManager, { SystemNotificationOptions } from "./notificationManager";
import TrayManager from "./trayManager";
import MenuManager from "./menuManager";

// The built directory structure
//
// ├─┬ dist-electron
// │ ├─┬ main
// │ │ └── index.js    > Electron-Main
// │ └─┬ preload
// │   └── index.mjs    > Preload-Scripts
// ├─┬ dist
// │ └── index.html    > Electron-Renderer
//
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
process.env.DIST_ELECTRON = join(__dirname, "..");
process.env.DIST = join(process.env.DIST_ELECTRON, "../dist");
process.env.PUBLIC = process.env.VITE_DEV_SERVER_URL
  ? join(process.env.DIST_ELECTRON, "../public")
  : process.env.DIST;

// 是否为开发环境
const isDev = process.env["NODE_ENV"] === "development";

// Disable GPU Acceleration for Windows 7
if (release().startsWith("6.1")) app.disableHardwareAcceleration();

// Set application name for Windows 10+ notifications
if (process.platform === "win32") app.setAppUserModelId(app.getName());

if (!app.requestSingleInstanceLock()) {
  app.quit();
  process.exit(0);
}

// Remove electron security warnings
// This warning only shows in development mode
// Read more on https://www.electronjs.org/docs/latest/tutorial/security
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

let win: BrowserWindow | null = null;
let quitting = false;

// 初始化管理器
let notificationManager: NotificationManager;
let trayManager: TrayManager;
let menuManager: MenuManager;

// Here, you can also use other preload
const preload = join(__dirname, "../preload/index.mjs");
const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = join(process.env.DIST, "index.html");

// 自动更新相关代码
autoUpdater.autoDownload = true; // 自动下载更新
autoUpdater.autoInstallOnAppQuit = true; // 退出时自动安装更新

// 设置自定义更新地址
const VITE_UPDATE_SERVER_URL = process.env.VITE_UPDATE_SERVER_URL || 'https://your-update-server.com'; // 替换为你的更新服务器地址

autoUpdater.setFeedURL({
  provider: 'generic',
  url: VITE_UPDATE_SERVER_URL
});

autoUpdater.on('update-available', (info) => {
  console.log('发现新版本:', info.version);
  // 静默下载更新
  autoUpdater.downloadUpdate().catch(err => {
    console.error('下载更新失败:', err);
  });
});

autoUpdater.on('update-downloaded', (info) => {
  console.log('更新已下载完成:', info.version);
  // 延迟几秒后自动重启并安装更新
  setTimeout(() => {
    setImmediate(() => autoUpdater.quitAndInstall());
  }, 3000);
});

autoUpdater.on('error', (err) => {
  console.error('自动更新出错:', err);
});

// IPC 处理器 - 允许渲染进程动态设置更新地址
ipcMain.handle("set-update-url", (_, updateUrl: string) => {
  autoUpdater.setFeedURL({
    provider: 'generic',
    url: updateUrl
  });
});

// 设置窗口事件
function setupWindowEvents(win: BrowserWindow) {
  // 最小化事件
  win.on("minimize", () => {
    // win.hide();
    // notificationManager.showNotification("应用程序已最小化到系统托盘");
  });

  // 关闭事件
  win.on("close", (event: Event) => {
    if (!quitting) {
      event.preventDefault();
      win.hide();
      // 这里不需要通知吧，因为用户已经看到了系统托盘的图标
      // notificationManager.showNotification("应用程序已最小化到系统托盘，仍在后台运行");
      return false;
    }
  });

  // 全屏事件
  win.on("enter-full-screen", () => menuManager.createMenu("退出全屏幕"));
  win.on("leave-full-screen", () => menuManager.createMenu());
}

// ... existing code ...
async function createWindow() {
  win = new BrowserWindow({
    width: 1024,
    height: 768,
    minWidth: 1024,
    minHeight: 768,
    title: "Main window",
    icon: join(process.env.PUBLIC, "favicon.ico"),
    webPreferences: {
      preload,
      nodeIntegration: false,
      contextIsolation: true
    }
  });

  // 更新管理器中的窗口引用
  notificationManager.setMainWindow(win);
  trayManager.setMainWindow(win);
  menuManager.setMainWindow(win);

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(url);
  } else {
    win.loadFile(indexHtml);
  }

  menuManager.createMenu();
  setupWindowEvents(win);

  // 添加右键菜单 - 正确的位置应该在这里
  win.webContents.on('context-menu', (_, params) => {
    const menu = Menu.buildFromTemplate([
      {
        label: '刷新',
        click: () => {
          win?.webContents.reload();
        }
      },
      {
        label: '开发者工具',
        click: () => {
          win?.webContents.toggleDevTools();
        }
      },
      {
        type: 'separator'
      },
      {
        label: '撤销',
        role: 'undo'
      },
      {
        label: '重做',
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        label: '剪切',
        role: 'cut'
      },
      {
        label: '复制',
        role: 'copy'
      },
      {
        label: '粘贴',
        role: 'paste'
      },
      {
        label: '全选',
        role: 'selectAll'
      }
    ]);

    menu.popup({ window: win });
  });

  win.webContents.on("did-finish-load", () => {
    win?.webContents.send("main-process-message", new Date().toLocaleString());
    // 应用启动后检查更新（仅在生产环境中）
    if (!isDev) {
      setTimeout(() => {
        autoUpdater.checkForUpdates().catch(err => {
          console.error('检查更新失败:', err);
        });
      }, 5000); // 延迟5秒检查更新，确保应用完全启动
    }
  });

  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith("https:")) shell.openExternal(url);
    return { action: "deny" };
  });
}
// ... existing code ...

// IPC 处理器
const windowHandlers = {
  minimize: () => win?.minimize(),
  hide: () => win?.hide(),
  show: () => win?.show()
};

Object.entries(windowHandlers).forEach(([channel, handler]) => {
  ipcMain.handle(`window-${channel}`, handler);
});

ipcMain.handle("open-win", (_, arg) => {
  const childWindow = new BrowserWindow({
    webPreferences: {
      preload,
      nodeIntegration: false,
      contextIsolation: true
    }
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    childWindow.loadURL(`${url}#${arg}`);
  } else {
    childWindow.loadFile(indexHtml, { hash: arg });
  }
});

ipcMain.handle("play-sound", (_, soundPath) => {
  try {
    if (win) {
      win.webContents.send("play-sound", soundPath);
      return { success: true };
    }
    return { success: false, error: "Main window not available" };
  } catch (error: any) {
    console.error("播放声音失败:", error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle("show-notification", (_, options: SystemNotificationOptions) => {
  if (!notificationManager) {
    return { success: false, error: "Notification manager not initialised" };
  }
  return notificationManager.showNotification(options);
});

// 应用生命周期
app.whenReady().then(async () => {
  try {
    // 初始化管理器
    notificationManager = new NotificationManager(win);
    trayManager = new TrayManager(win, isDev);
    menuManager = new MenuManager(win, isDev);

    await createWindow();
    trayManager.createTray();
  } catch (error) {
    console.error("初始化失败:", error);
    app.quit();
  }
});

app.on("before-quit", () => {
  quitting = true;
});

app.on("window-all-closed", () => {
  win = null;
  if (process.platform !== "darwin") app.quit();
});

app.on("second-instance", () => {
  if (win) {
    if (win.isMinimized()) win.restore();
    win.focus();
  }
});
